package com.glory.dgcpcpda.activity.cpc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.glory.dgcpcpda.activity.mfg.DAWorkBeginActivity;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.AlarmInfo;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.glory.dgcpcpda.utils.ScaleView;
import com.glory.dgcpcpda.R;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import butterknife.BindView;

public class PracticeActivity extends AppCompatActivity {
    private ScaleView mScaleView;

    private Bitmap mBitmap;
    private int fileLength;
    private  final String urlString = "http://192.168.40.223:8080/auto_sync_date/image";
    private TextView btn;
    private Bitmap bm;
    protected static final int CHANGE_UI = 1;
    protected static final int ERROR = 2;
    private FreeUI_ClearEditText editText;
    private String str;
    private ScaleView imageView;
    private MyHandler handler1;
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            imageView = (ScaleView)findViewById(R.id.scaleView);
            System.out.println("###########4");
            imageView.setImageBitmap((Bitmap)msg.obj);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cpc_practise);
        handler1 = new MyHandler();
        // Button button = (Button) findViewById(R.id.btn2);
        editText=(FreeUI_ClearEditText) findViewById(R.id.etEqpWork);
        //imageView = (ScaleView)findViewById(R.id.scaleView);
        System.out.println("CREATE!!!!!");
       editText.addTextChangedListener(textWatcher);
        initEdit2(editText,s ->getData(editText.getText().toString().trim()) );

        //TextView button = (TextView) findViewById(R.id.tvBaseSubmit);
       /* button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String lotId=  editText.getText().toString().trim();
                if(StringUtils.isEmpty(lotId)){
                    System.out.println("请扫描随件单");
                    Toast.makeText(PracticeActivity.this, "请输入批次号！", Toast.LENGTH_SHORT).show();
                }else{
                    getData(lotId);
                }

            }
        });*/
    }
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d("TAG","beforeTextChanged--------------->");
        }
        @Override
        public void afterTextChanged(Editable s) {
            Log.d("TAG","afterTextChanged--------------->");

        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            Log.d("TAG","onTextChanged--------------->");
            String lotId=  editText.getText().toString().trim();
            if(StringUtils.isEmpty(lotId)){
                Bitmap bm = BitmapFactory.decodeStream(null);
                Message msg = new Message();
                msg.obj = bm;
                handler1.sendMessage(msg);

            }

        }

    };
    public void getData(String lotId){
        System.out.println("这里是监听手机的回车事件2");
        LotUtils.searchLotInfo(PracticeActivity.this, lotId, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //2:把网址封装为一个URL对象
                            URL url = new URL(urlString);
                            //3:获取客户端和服务器的连接对象，此时还没有建立连接
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            //4:初始化连接对象
                            conn.setRequestMethod("POST");
                            conn.setDoInput(true);//发送POST请求必须设置允许输出
                            conn.setDoOutput(true);
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("Charset", "utf-8");
                            String data = "pxt=" + URLEncoder.encode(response.getWIRINGNO(), "UTF-8");
                            conn.setRequestProperty("Content-Length",
                                    String.valueOf(data.getBytes().length));
                            OutputStream os = conn.getOutputStream();
                            os.write(data.getBytes());
                            os.flush();
                            //设置连接超时
                            conn.setConnectTimeout(8000);
                            //设置读取超时
                            conn.setReadTimeout(8000);
                            //5:发生请求，与服务器建立连接
                            conn.connect();
                            //如果响应码为200，说明请求成功
                            if(conn.getResponseCode() == 200)
                            {
                                //获取服务器响应头中的流
                                InputStream is = conn.getInputStream();
                                //读取流里的数据，构建成bitmap位图
                                Bitmap bm = BitmapFactory.decodeStream(is);
                                Message msg = new Message();
                                msg.obj = bm;
                                handler1.sendMessage(msg);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }

            @Override
            public void onFail(Throwable t) {
                System.out.println("返回失败！");

                Bitmap bm = BitmapFactory.decodeStream(null);
                Message msg = new Message();
                msg.obj = bm;
                handler1.sendMessage(msg);
            }

        });

    }
    protected void initEdit2(EditText editText, final BaseActivity.editTextListener listener){
        editText.setImeOptions(EditorInfo.IME_ACTION_GO);
        editText.setSingleLine(true);
        editText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (EditorInfo.IME_ACTION_GO == i) {
                String text = editText.getText().toString();
                //转大写并触发扫描效果

                System.out.println("############1");
                editText.getText().clear();
                System.out.println("############2");
                editText.setText(text);
                editText.setSelection(editText.getText().length());
                return true;
            }
            return false;
        });
        FreeApi_EditTextUtils.setEditTextListener(editText, this, s -> {
            if (listener != null){
                System.out.println("############3");
                listener.onTextChangeListener(s);
            }
        });
    }

}


